package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-12-05 21:46
 **/
public class LeetCode22 {



    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<>();
        recur(n, 0, 0, new StringBuilder(), list);
        return list;
    }

    /**
     *
     * @param n 括号对数
     * @param leftNum 左括号数
     * @param rightNum 右括号数
     * @param builder 字符串构造
     * @param list 存储所有可能的括号对
     */
    void recur(int n, int leftNum, int rightNum, StringBuilder builder, List<String> list) {
        if (builder.length() == n * 2) {
            list.add(builder.toString());
            return;
        }

        if (leftNum < n) {
            builder.append("(");
            recur(n, leftNum + 1, rightNum, builder, list);
            builder.deleteCharAt(builder.length() - 1);
        }

        if (rightNum < leftNum) {
            builder.append(")");
            recur(n, leftNum, rightNum + 1, builder, list);
            builder.deleteCharAt(builder.length() - 1);
        }
    }

    public static void main(String[] args) {
        LeetCode22 code = new LeetCode22();
        code.generateParenthesis(3);
    }

}
